<template>
  <px-card shadow="never">
    <!-- <CustomTabs :tabList="options" :activeName="activeName" @tabSelect="handelTabSelected" />
      -->
    <px-tabs v-model="activeName" class="equipment-tabs" @tab-click="handelTabSelected">
      <px-tab-pane v-for="item in options" :key="item.label" :name="item?.name">
        <template #label>
          <p class="pane-bottom">{{ item?.label }}</p>
          <p class="pane-line" />
        </template>
      </px-tab-pane>
    </px-tabs>
    <px-form ref="formRef" class="custom-form-ui-new" inline :model="queryParams" label-position="right" label-width="80px">
      <px-form-item label="内容搜索">
        <px-input v-model="queryParams.messageContent" placeholder="请输入关键词进行搜索" autocomplete="off" clearable @keyup.enter="queryTable" />
      </px-form-item>
      <px-form-item label="消息类型">
        <px-select v-model="queryParams.messageType" clearable placeholder="请选择消息类型">
          <px-option v-for="item in messageTypeList" :key="item.id" :value="item.value" :label="item.name" />
        </px-select>
      </px-form-item>
      <px-form-item label="消息时间">
        <px-date-picker
          v-model="queryParams.time"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </px-form-item>
      <px-form-item>
        <px-button type="primary" @click="queryTable">查询</px-button>
        <px-button @click="resetTable">重置</px-button>
      </px-form-item>
    </px-form>
    <px-table :data="tableData" class="spare-parts-table" height="calc(100vh - 361px)" border>
      <px-table-column prop="messageTypeName" label="消息类型" min-width="120" show-overflow-tooltip />
      <px-table-column prop="messageContent" label="内容" min-width="500" show-overflow-tooltip>
        <template #default="scope">
          <div
            v-if="scope.row.redirectUrl"
            :style="{ color: scope.row.processStatus === 'UNDO' ? '#1890ff' : 'rgba(0,0,0,.4)', cursor: 'pointer' }"
            @click="handleDetail(scope.row)"
          >
            {{ scope.row.messageContent }}
          </div>
          <div v-else>{{ scope.row.messageContent }}</div>
        </template>
      </px-table-column>
      <px-table-column prop="createTime" label="发送时间" min-width="180" show-overflow-tooltip />
      <px-table-column prop="readRatio" label="已读比例" min-width="80" show-overflow-tooltip />
    </px-table>
    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="queryTable" />
  </px-card>
</template>

<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { queryById, queryUndoCount, setMessageRead } from "@/api/message";
import { useCountsStore } from "@/store/modules/counts";
import { getToken } from "@/utils/auth";
import { onMounted, reactive, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";

defineOptions({
  name: "ALL_MESSAGE"
});

const route = useRoute();
const router = useRouter();
const countsStore = useCountsStore();

const data = reactive<Record<string, any>>({
  activeName: "ALL",
  options: [],
  queryParams: {
    pageSize: 20,
    pageNum: 1
  },
  tableData: [],
  total: 0,
  messageTypeList: []
});

const { activeName, options, queryParams, tableData, total, messageTypeList } = toRefs(data);

const handleDetail = async row => {
  const { redirectUrl, messageId, messageType } = row;
  await setMessageRead({ messageId });
  await getTotal();
  await queryTable();
  // 设备保养因为是iframe嵌套模式，消息跳转时需要带上当前登录人的token
  if (messageType === "EQP_MAINTENANCE") {
    const token = getToken().accessToken || "";
    if (redirectUrl?.includes("http")) {
      window.open(`${redirectUrl}&ssoToken=${token}`);
    } else {
      router.push(`${redirectUrl}&ssoToken=${token}`);
    }
  } else {
    if (redirectUrl?.includes("http")) {
      window.open(redirectUrl);
    } else {
      router.push(redirectUrl);
    }
  }
};

const getMessageType = async () => {
  const res = await queryDictData({ typeCode: "MESSAGE_TYPE" });
  messageTypeList.value = res || [];
};

const getTotal = async () => {
  const res = await queryUndoCount({ messageCategory: "NOTICE" });
  options.value = [
    {
      name: "ALL",
      label: `全部消息（${res.totalNumber || 0}）`
    },
    {
      name: "UNDO",
      label: `未读消息（${res.unreadNumber || 0}）`
    },
    {
      name: "DONE",
      label: `已读消息（${res.readNumber || 0}）`
    }
  ];
  await countsStore.setMsgCount(res);
};

// 查询巡检清单
const queryTable = async () => {
  const { time } = queryParams.value;
  const data = await queryById({
    processStatus: activeName.value === "ALL" ? "" : activeName.value,
    messageCategory: "NOTICE",
    startTime: time && time[0] ? `${time[0]} 00:00:00` : "",
    endTime: time && time[1] ? `${time[1]} 23:59:59` : "",
    ...queryParams.value
  });
  tableData.value = data?.data || [];
  total.value = data?.total || 0;
};

// 重置筛选条件和巡检清单
const resetTable = async () => {
  queryParams.value = {
    messageType: "",
    messageContent: "",
    className: "",
    pageNum: 1,
    pageSize: 10
  };
  queryTable();
};

// 切换tabs调用接口
const handelTabSelected = tab => {
  activeName.value = tab.paneName;
  queryTable();
};

onMounted(() => {
  getMessageType();
  const key = route.query.active;
  if (key) {
    activeName.value = key;
  }
  queryTable();
  getTotal();
});
</script>
